package com.richest.api.controller.cn.client.order;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;

import com.richest.api.controller.form.EatOrderForm;
import com.richest.api.service.IAdmartService;
import com.richest.api.service.IDiningTableService;
import com.richest.api.service.IEatOrderNumberService;
import com.richest.api.service.IEatOrderService;
import com.richest.api.service.IFoodOrderService;
import com.richest.api.service.IGoodService;
import com.richest.api.service.IUserExtensionService;
import com.richest.api.utils.ClientCNCommonUtils;
import com.richest.bean.AdmartBean;
import com.richest.bean.DiningTableBean;
import com.richest.bean.EatOrderBean;
import com.richest.bean.FoodOrderBean;
import com.richest.bean.GoodBean;
import com.richest.bean.UserExtensionBean;
import com.richest.util.CallResults;
import com.richest.util.StringUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import java_cup.runtime.virtual_parse_stack;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

/**
 * 就餐订单 cn_eat_order 后端接口
 * 
 * @author zhaohongchao
 * @email 70375739@qq.com
 * @date 2019-02-28 14:15:26
 */
@RestController
@RequestMapping("eatorderController")
@Api(value = "就餐订单接口")
@EnableAutoConfiguration
public class ApiEatOrderController {
	@Autowired
	private IEatOrderService eatOrderService;

	@Autowired
	private IFoodOrderService foodOrderService;

	@Autowired
	private IGoodService goodService;

	@Autowired
	private IAdmartService admartService;

	@Autowired
	private IEatOrderNumberService eatOrderNumberService;

	@Autowired
	private IUserExtensionService userExtensionService;

	@Autowired
	private IDiningTableService diningTableService;

	/**
	 * 根据状态获取订单列表
	 */
	@RequestMapping(value = "getEatOrderList", produces = "application/json;charset=UTF-8")
	@ApiOperation(notes = "根据状态获取订单列表", value = "根据状态获取订单列表", httpMethod = "GET")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "status", value = "订单状态：00:全部订单；01 未支付；02 已支付待商户接单；03商户已接单； 04 商户已拒绝； 05 订单支付完成； 06 订单未支付取消； 07 商户进行退款审核； 08 商户拒绝退款； 09 订单已退款", required = true, paramType = "query", dataType = "Integer"),
			@ApiImplicitParam(name = "userId", value = "用户ID", required = true, paramType = "query", dataType = "String") })
	public CallResults getEatOrderList(@RequestParam Integer status, @RequestParam String userId) {
		return CallResults.ok().put("data", eatOrderService.selectEatOrderList(status, userId));
	}

	/**
	 * 保存
	 */
	@RequestMapping(value = "saveOrder", produces = "application/json;charset=UTF-8")
	@ApiOperation(notes = "生成就餐订单", value = "生成就餐订单", httpMethod = "POST")
	@ApiImplicitParam(name = "form", value = "订单参数", required = true, dataType = "EatOrderForm")
	@Transactional
	public CallResults saveOrder(@RequestBody EatOrderForm form) throws ParseException {
		String strReturnMessage = "";
		String strUserId = form.getUser_id();
		String strAdmartId = form.getAdmart_id();
		String strDiningTable = form.getDining_table_id();
		String strUserExtensionId = form.getUser_extension_id();

		if (StringUtil.isNullOrEmpty(strUserId)) {
			return CallResults.error("用户ID不能为空");
		}
		if (StringUtil.isNullOrEmpty(strAdmartId)) {
			return CallResults.error("店铺ID不能为空");
		}

		EatOrderBean eatOrderBean = new EatOrderBean();

		Long lAdmartId = Long.parseLong(strAdmartId);
		Long lUserId = Long.parseLong(strUserId);

		UserExtensionBean userExtensionBean = null;
		if (null != strUserExtensionId && !"".equals(strUserExtensionId)) {
			Long lUserExtensionId = Long.parseLong(strUserExtensionId);
			userExtensionBean = userExtensionService.selectById(lUserExtensionId);
		}

		AdmartBean admartBean = admartService.selectById(lAdmartId);

		int iSerialNumber = 1;
		String strSerialNumber = ClientCNCommonUtils.getSerialNumber(eatOrderNumberService, lAdmartId,
				admartBean.getBiz_type(), admartBean.getAdmart_code());
		eatOrderBean.setCreate_by(lUserId);
		eatOrderBean.setCreate_time(new Date());
		eatOrderBean.setAdmart_id(lAdmartId);
		eatOrderBean.setDescription(form.getDescription());
		eatOrderBean.setBegin_time(form.getBegin_time());
		eatOrderBean.setPhone(form.getPhone());
		eatOrderBean.setUser(form.getUser());

		if (null != strDiningTable && !"".equals(strDiningTable)) {
			Long lDiningTableId = Long.parseLong(strDiningTable);
			// 如果是点餐
			if ("0".equals(form.getType())) {
				DiningTableBean diningTableBean = new DiningTableBean();
				diningTableBean.setDining_table_id(lDiningTableId);
				diningTableBean = diningTableService.selectOne(diningTableBean);
				// 所选餐位不存在
				if (diningTableBean != null) {
					diningTableBean = diningTableService.getNext(lAdmartId);
					if (null == diningTableBean) {
						return CallResults.error("没有桌/包房信息");
					}
					eatOrderBean.setDining_table_id(diningTableBean.getDining_table_id());
					strReturnMessage = "您选的包房/桌已被使用，已随机给您分配了其他座位";
				} else {
					// 所选的餐位信息正确
					eatOrderBean.setDining_table_id(lDiningTableId);
				}
			} else {
				// 如果是加菜，原餐位和新订单关联
				eatOrderBean.setDining_table_id(lDiningTableId);
			}

		} else {
			// 没有选择包房/桌信息，随机分配
			DiningTableBean diningTableBean = diningTableService.getNext(lAdmartId);
			if (null == diningTableBean) {
				return CallResults.error("没有桌/包房信息");
			}
			eatOrderBean.setDining_table_id(diningTableBean.getDining_table_id());
		}

		eatOrderBean.setInvoice("0");
		eatOrderBean.setStatus(1);
		eatOrderBean.setStatus_name("未支付");
		eatOrderBean.setStatus_desc("订单将在15分钟后自动取消，请尽快支付");
		eatOrderBean.setTotal_money(new BigDecimal("0"));
		eatOrderBean.setPay_money(new BigDecimal("0"));

		eatOrderBean.setEat_serial_number(strSerialNumber);

		List<Map<String, Object>> lstGood = form.getGood_list();
		for (int i = 0; i < lstGood.size(); i++) {
			long lGoodId = Long.valueOf(String.valueOf(lstGood.get(i).get("good_id")));
			int iCount = Integer.valueOf(String.valueOf(lstGood.get(i).get("count")));

			GoodBean goodBean = goodService.selectById(lGoodId);
			for (int j = 0; j < iCount; j++) {
				FoodOrderBean foodOrderBean = new FoodOrderBean();
				foodOrderBean.setCount(1);
				foodOrderBean.setCreate_by(lUserId);
				foodOrderBean.setCreate_time(new Date());
				foodOrderBean.setImage(goodBean.getPic_img());
				foodOrderBean.setFood_id(goodBean.getGood_id().longValue());
				foodOrderBean.setFood_name(goodBean.getGood_name());
				foodOrderBean.setPrice(goodBean.getMin_price());
				foodOrderBean.setStatus(1);
				foodOrderBean.setStatus_name("未支付");
				foodOrderBean.setTotal_money(goodBean.getMin_price());
				foodOrderBean.setEat_serial_number(strSerialNumber);
				foodOrderBean.setFood_serial_number(strSerialNumber + String.format("%04d", i + 1));
				foodOrderBean.setPay_price(foodOrderBean.getPrice());
				foodOrderBean.setPay_money(foodOrderBean.getTotal_money());

				/*
				 * 如果是赠送金或打折卡，折扣单品订单，允许单品退单或整单退单
				 */
				if (null != userExtensionBean) {
					if (3 == userExtensionBean.getType() || 4 == userExtensionBean.getType()) {
						eatOrderBean.setUser_extension_id(userExtensionBean.getId());
						ClientCNCommonUtils.getFoodOrderExtension(userExtensionBean, foodOrderBean);
					} else {
						foodOrderBean.setPay_price(foodOrderBean.getPrice());
						foodOrderBean.setPay_money(foodOrderBean.getPrice());
					}
				} else {
					foodOrderBean.setPay_price(foodOrderBean.getPrice());
					foodOrderBean.setPay_money(foodOrderBean.getPrice());
				}

				foodOrderService.insert(foodOrderBean);

				eatOrderBean.setTotal_money(eatOrderBean.getTotal_money().add(foodOrderBean.getTotal_money()));
				eatOrderBean.setPay_money(eatOrderBean.getPay_money().add(foodOrderBean.getPay_money()));
			}
		}

		/*
		 * 如果是优惠卷或满减卷，直接折扣就餐订单，并且不允许退单品，只能整单退
		 */
		if (null != userExtensionBean) {
			if (1 == userExtensionBean.getType() || 2 == userExtensionBean.getType()) {
				eatOrderBean.setUser_extension_id(userExtensionBean.getId());
				eatOrderBean.setPay_money(
						ClientCNCommonUtils.getEatOrderExtension(eatOrderBean.getPay_money(), userExtensionBean));
				userExtensionBean.setStatus(2);
			}
			userExtensionService.update(userExtensionBean);
		}
		eatOrderService.insert(eatOrderBean);
		strReturnMessage = "订单生成成功";
		return CallResults.ok(eatOrderBean.getEat_serial_number());
	}

	/**
	 * 整单退款
	 */
	@RequestMapping(value = "applyRefundEatOrdre", produces = "application/json;charset=UTF-8")
	@ApiOperation(notes = "整单退款", value = "整单退款", httpMethod = "GET")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "eatSerialNumber", value = "订单号", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "reason", value = "退款原因", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "userId", value = "退款人id", required = true, paramType = "query", dataType = "String") })
	@Transactional
	public CallResults applyRefundEatOrdre(@RequestParam String eatSerialNumber, @RequestParam String reason,
			@RequestParam String userId) {
		// 查看传入的订单是否正确
		EatOrderBean eatOrderBean = eatOrderService.queryByEatSerialNumber(eatSerialNumber, 5);
		if (eatOrderBean == null) {
			return CallResults.error("不存在有效的订单信息");
		}
		// 退菜列表
		List<Map<String, String>> refundList = new ArrayList<>();
		// 获取就餐订单下菜品列表
		Collection<FoodOrderBean> colFoodOrder = foodOrderService.selectByEatSerialNumber(eatSerialNumber);
		for (FoodOrderBean foodOrderBean : colFoodOrder) {
			Map<String, String> foodOrder = new HashMap<>();
			foodOrder.put("food_serial_number", foodOrderBean.getFood_serial_number());
			foodOrder.put("reason", reason);
			refundList.add(foodOrder);
		}
		// 移除所有菜品
		foodOrderService.applyRefundOrder(refundList, userId, 7, "商户进行退单审核");
		// 移除订单
		eatOrderService.appapplyRefundOrder(eatSerialNumber, 5, reason, userId, 7, "商户进行退款审核", "等待商家审核，请联系商家确认");

		return CallResults.ok();
	}

	/**
	 * 单品退款
	 */
	@RequestMapping(value = "applyRefundFoodOrder", produces = "application/json;charset=UTF-8")
	@ApiOperation(notes = "单品退款", value = "单品退款", httpMethod = "GET")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "eatSerialNumber", value = "订单号", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "foodId", value = "退款原因", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "reason", value = "退款人id", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "userId", value = "退款人id", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "count", value = "退款人id", required = true, paramType = "query", dataType = "String") })
	@Transactional
	public CallResults applyRefundFoodOrder(@RequestParam String eatSerialNumber, @RequestParam String foodId,
			@RequestParam String reason, @RequestParam String userId, @RequestParam Integer count) {
		// 查看传入的订单是否正确
		EatOrderBean eatOrderBean = eatOrderService.queryByEatSerialNumber(eatSerialNumber, 5);
		if (eatOrderBean == null) {
			return CallResults.error("不存在有效的订单信息");
		}
		// 退菜列表
		List<Map<String, String>> refundList = new ArrayList<>();

		// 就餐订单下的所有菜品
		Collection<FoodOrderBean> colFoodOrder = foodOrderService.selectByEatSerialNumber(eatSerialNumber);

		// 需要退的菜品列表
		List<String> lstFoodOrder = foodOrderService.selectFoodSerialNumberByFoodId(foodId, eatSerialNumber, count);

		for (String foodSerialNumber : lstFoodOrder) {
			// 移除菜品订单
			for (FoodOrderBean foodOrderBean : colFoodOrder) {
				if (foodSerialNumber.equals(foodOrderBean.getFood_serial_number())) {
					colFoodOrder.remove(foodOrderBean);
					break;
				}
			}
		}
		// 生成退菜列表
		for (

		String foodSerialNumber : lstFoodOrder) {
			Map<String, String> map = new HashMap<>();
			map.put("food_serial_number", foodSerialNumber);
			map.put("reason", reason);
			refundList.add(map);
		}
		// 移除菜品
		foodOrderService.applyRefundOrder(refundList, userId, 7, "商户进行退单审核");
		// 如果就餐订单下没有菜品列表，移除就餐订单
		if (colFoodOrder.size() <= 0) {
			eatOrderService.appapplyRefundOrder(eatSerialNumber, 5, reason, userId, 7, "商户进行退款审核", "等待商家审核，请联系商家确认");
		}

		return CallResults.ok();
	}

	/**
	 * 取消订单
	 */
	@RequestMapping(value = "cancelOrder", produces = "application/json;charset=UTF-8")
	@ApiOperation(notes = "取消订单", value = "取消订单", httpMethod = "GET")
	@ApiImplicitParam(name = "eatSerialNumber", value = "订单号", required = true, paramType = "query", dataType = "String")
	public CallResults cancelOrder(@RequestParam String eatSerialNumber) {
		EatOrderBean eatOrderBean = eatOrderService.queryByEatSerialNumber(eatSerialNumber, null);
		if (null == eatOrderBean) {
			return CallResults.error("不存在有效的订单");
		}

		// 桌/包房状态设置成未使用
		diningTableService.updateStatus(eatOrderBean.getDining_table_id(), 1, "未使用", null, null);

		eatOrderService.appapplyRefundOrder(eatSerialNumber, null, null, eatOrderBean.getCreate_by().toString(), 6,
				"订单未支付取消", "已超过15分钟，请重新下单");

		Map<String, Object> mapEatOrder = eatOrderService.getEatOrderBySerialNumber(eatSerialNumber);

		return CallResults.ok();
	}

	/**
	 * 根据订单号获取订单详情
	 */
	@RequestMapping(value = "getEatOrderBySerialNumber", produces = "application/json;charset=UTF-8")
	@ApiOperation(notes = "根据订单号获取订单详情", value = "根据订单号获取订单详情", httpMethod = "GET")
	@ApiImplicitParam(name = "serialNumber", value = "订单号", required = true, paramType = "query", dataType = "String")
	public CallResults getEatOrderBySerialNumber(@RequestParam String serialNumber) {
		return eatOrderService.getEatOrderBySerialNumber(serialNumber);
	}

}
